package com.tedu.food.common.listener;

import com.tedu.food.sys.dao.OrderItemDao;
import com.tedu.food.sys.dao.OrderMasterDao;
import com.tedu.food.sys.entity.OrderMaster;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 监听key过期执行订单超时删除操作
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends  KeyExpirationEventMessageListener {
    @Autowired private OrderMasterDao orderMasterDao; @Autowired private OrderItemDao orderItemDao;
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        if(expiredKey.startsWith("orderId")){
            int id = Integer.parseInt(expiredKey.substring(7));
            OrderMaster orderMaster = orderMasterDao.findOrderMasterById(id);
            if(orderMaster == null)
                log.info("id为" + id +"的待支付订单被顾客手动取消了");
            else if(orderMaster.getOrderStatus() == 1)
                log.info("id为" + id +"的待支付订单被顾客支付了");
            else{
                //取消超时待支付订单
                orderMasterDao.deleteOrderMasterById(id);
                orderItemDao.deleteOrderItemsByOrderId(id);
                log.info("id为" + id +"的待支付订单被取消了");
            }
        }
    }
}